package com.nstc.demo.exception;

import java.util.HashMap;
import java.util.Map;

import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;

import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.nstc.demo.util.Result;
import com.nstc.demo.util.ResultGenerator;

/**
 * 
 * @ClassName: GlobalExceptionHandler
 * @Description: 处理全局异常
 * @author fbb
 * @date 2021年7月30日
 *
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

	
	/**
	 * 
	    * @Title: handleParameterVerificationException
	    * @Description: 捕获参数校验失败的异常，并将message返回前端
	    * @param  e 异常类型
	    * @return Result    返回类型
	    * @throws
	 */
	@ResponseStatus(code = HttpStatus.BAD_REQUEST)
	@ExceptionHandler(value = { BindException.class, ValidationException.class, MethodArgumentNotValidException.class })
	public Result handleParameterVerificationException(Exception e) {
		String msg = null;
		// BindException
		if (e instanceof BindException) {
			// getFieldError获取的是第一个不合法的参数
			FieldError fieldError = ((BindException) e).getFieldError();
			if (fieldError != null) {
				msg = fieldError.getDefaultMessage();
			}
			// MethodArgumentNotValidException
		} else if (e instanceof MethodArgumentNotValidException) {
			BindingResult bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
			// getFieldError获取的是第一个不合法的参数
			FieldError fieldError = bindingResult.getFieldError();
			if (fieldError != null) {
				msg = fieldError.getDefaultMessage();
			}
			// ValidationException 的子类异常ConstraintViolationException
		} else if (e instanceof ConstraintViolationException) {
			/*
			 * ConstraintViolationException的e.getMessage()形如 {方法名}.{参数名}: {message}
			 * 这里只需要取后面的message即可
			 */
			msg = e.getMessage();
			if (msg != null) {
				int lastIndex = msg.lastIndexOf(':');
				if (lastIndex >= 0) {
					msg = msg.substring(lastIndex + 1).trim();
				}
			}
			/// ValidationException 的其它子类异常
		} else {
			msg = "处理参数时异常";
		}
		return ResultGenerator.genFailResult(msg);
	}

}
